<template>
  <div class="page-container">
    <!-- Main Content -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- Payment Password Settings -->
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex; align-items: center; justify-content: space-between;">
                <span style="font-size: 16px; font-weight: 600;">Payment Password Settings</span>
                <el-tag :type="hasPayoutPassword ? 'success' : 'warning'">
                  {{ hasPayoutPassword ? 'Set' : 'Not Set' }}
                </el-tag>
              </div>
            </template>

            <div style="margin-bottom: 20px;">
              <el-alert
                :title="hasPayoutPassword ? 'Payment Password Set' : 'Please Set Payment Password'"
                :type="hasPayoutPassword ? 'success' : 'warning'"
                :description="hasPayoutPassword ? 'Payment password is used to confirm payment orders and ensure payment security.' : 'Payment password is used to confirm payment orders. Please set a secure password.'"
                show-icon
                :closable="false"
                style="margin-bottom: 20px;"
              />
            </div>

            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="120px"
            >
              <el-form-item
                v-if="hasPayoutPassword"
                label="Current Password"
                prop="currentPassword"
              >
                <el-input
                  v-model="passwordForm.currentPassword"
                  type="password"
                  placeholder="Please enter current payment password"
                  show-password
                  maxlength="50"
                />
              </el-form-item>

              <el-form-item
                :label="hasPayoutPassword ? 'New Password' : 'Payment Password'"
                prop="newPassword"
              >
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="Please enter new payment password (6-50 characters)"
                  show-password
                  maxlength="50"
                />
              </el-form-item>

              <el-form-item label="Confirm Password" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="Please enter the new password again"
                  show-password
                  maxlength="50"
                />
              </el-form-item>

              <el-form-item style="margin-top: 30px;">
                <el-button
                  type="primary"
                  size="large"
                  @click="handleSetPassword"
                  :loading="isSubmitting"
                >
                  <el-icon class="el-icon--left"><Lock /></el-icon>
                  {{ hasPayoutPassword ? 'Update Payment Password' : 'Set Payment Password' }}
                </el-button>
                <el-button size="large" @click="handleReset">
                  Reset Form
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- Help Information -->
        <el-col :span="12">
          <el-card shadow="hover" style="margin-bottom: 20px;">
            <template #header>
              <div style="display: flex; align-items: center;">
                <el-icon style="margin-right: 8px;"><InfoFilled /></el-icon>
                <span>Security Tips</span>
              </div>
            </template>

            <div class="help-content">
              <h4>Payment Password Usage</h4>
              <ul>
                <li>Payment password is required when confirming payment orders</li>
                <li>Payment password is separate from login password for enhanced security</li>
                <li>Only administrator role can set payment password</li>
              </ul>

              <h4>Password Security Requirements</h4>
              <ul>
                <li>Password length should be 6-50 characters</li>
                <li>Recommend including uppercase, lowercase letters, numbers and special characters</li>
                <li>Should not be the same as login password</li>
                <li>Change password regularly</li>
              </ul>

              <h4>Important Reminders</h4>
              <ul>
                <li>Please remember your payment password</li>
                <li>Do not share password with others</li>
                <li>If you forget the password, please contact system administrator</li>
                <li>Password takes effect immediately after setting</li>
              </ul>
            </div>
          </el-card>

          <!-- Operation History -->
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex; align-items: center;">
                <el-icon style="margin-right: 8px;"><Clock /></el-icon>
                <span>Operation Records</span>
              </div>
            </template>

            <div class="history-content">
              <el-timeline>
                <el-timeline-item
                  timestamp="Current"
                  type="primary"
                  icon="Setting"
                >
                  Configuring payment password settings
                </el-timeline-item>
                <el-timeline-item
                  v-if="hasPayoutPassword"
                  timestamp="Completed"
                  type="success"
                  icon="Check"
                >
                  Payment password has been set
                </el-timeline-item>
                <el-timeline-item
                  v-else
                  timestamp="Pending"
                  type="warning"
                  icon="Warning"
                >
                  Payment password not set yet
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Lock, InfoFilled, Clock } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { trpc } from '../utils/trpc'

// Reactive data
const passwordFormRef = ref<FormInstance>()
const isSubmitting = ref(false)
const hasPayoutPassword = ref(false)

// Form data
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// Form validation rules
const passwordRules: FormRules = {
  currentPassword: [
    { required: true, message: 'Please enter current payment password', trigger: 'blur' },
    { min: 6, max: 50, message: 'Password length should be 6-50 characters', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: 'Please enter new payment password', trigger: 'blur' },
    { min: 6, max: 50, message: 'Password length should be 6-50 characters', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: 'Please confirm new password', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('Two passwords do not match'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// Dynamic rules - current password required when password already exists
const getDynamicRules = () => {
  if (hasPayoutPassword.value) {
    return passwordRules
  } else {
    // Current password not required when setting password for the first time
    const rules = { ...passwordRules }
    delete rules.currentPassword
    return rules
  }
}

// Methods
const checkPayoutPasswordStatus = async () => {
  try {
    const result = await trpc.payout.checkPayoutPassword.query()
    if (result.success) {
      hasPayoutPassword.value = result.data.hasPayoutPassword
    }
  } catch (error: any) {
    console.error('Check payout password status error:', error)
    ElMessage.error('Failed to check payment password status')
  }
}

const handleSetPassword = async () => {
  if (!passwordFormRef.value) return

  const valid = await passwordFormRef.value.validate().catch(() => false)
  if (!valid) {
    ElMessage.error('Please check if the form is filled correctly')
    return
  }

  // Confirm setting
  const action = hasPayoutPassword.value ? 'update' : 'set'
  const actionText = hasPayoutPassword.value ? 'Update' : 'Set'
  const confirmed = await ElMessageBox.confirm(
    `Confirm to ${action} payment password? The ${action} will take effect immediately.`,
    `Confirm ${actionText}`,
    {
      confirmButtonText: `Confirm ${actionText}`,
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).catch(() => false)

  if (!confirmed) return

  isSubmitting.value = true

  try {
    const result = await trpc.payout.setPayoutPassword.mutate({
      newPassword: passwordForm.newPassword,
      currentPassword: hasPayoutPassword.value ? passwordForm.currentPassword : undefined,
    })

    if (result.success) {
      ElMessage.success(`Payment password ${action}d successfully!`)
      handleReset()
      await checkPayoutPasswordStatus()
    } else {
      ElMessage.error(result.message || `Failed to ${action} payment password`)
    }
  } catch (error: any) {
    console.error('Set payout password error:', error)
    ElMessage.error(error.message || `Failed to ${action} payment password`)
  } finally {
    isSubmitting.value = false
  }
}

const handleReset = () => {
  passwordFormRef.value?.resetFields()
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
}

// Lifecycle
onMounted(async () => {
  await checkPayoutPasswordStatus()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.main-content {
  margin-top: 0;
}

.help-content h4 {
  margin: 16px 0 8px 0;
  color: #333;
  font-size: 14px;
}

.help-content ul {
  margin: 0 0 16px 0;
  padding-left: 18px;
}

.help-content li {
  margin-bottom: 4px;
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.history-content {
  padding: 10px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-timeline) {
  padding-left: 0;
}
</style>